package sufutian.com.ibm_waston;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.ibm.watson.developer_cloud.http.HttpMediaType;
import com.ibm.watson.developer_cloud.http.ServiceCallback;
import com.ibm.watson.developer_cloud.speech_to_text.v1.SpeechToText;
import com.ibm.watson.developer_cloud.speech_to_text.v1.model.RecognizeOptions;
import com.ibm.watson.developer_cloud.speech_to_text.v1.model.SpeechAlternative;
import com.ibm.watson.developer_cloud.speech_to_text.v1.model.SpeechResults;
import com.ibm.watson.developer_cloud.speech_to_text.v1.model.SpeechTimestamp;
import com.ibm.watson.developer_cloud.speech_to_text.v1.model.Transcript;
import com.ibm.watson.developer_cloud.speech_to_text.v1.websocket.RecognizeCallback;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * Created by sufutian on 2017/6/29.
 */

public class WatsonSpeechTwo implements RecognizeCallback {

    private SpeechToText IBmService;
    private RecognizeOptions options;

    private String TAG = "WatsonSpeechTwo";

    private ArrayList<KDBean> resultList = new ArrayList<>();

    Context context;

    private final int SUCCESS = 0;

    private Handler handler = new Handler(Looper.myLooper(), new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            switch (message.what) {
                case 0:
                    if (lisenter != null) {
                        lisenter.onSuccess(resultList);
                    }
                    break;
                default:
                    break;
            }

            return false;
        }
    });


    public WatsonSpeechTwo(Context context) {
        this.context = context;
    }

    public void startRecognize(String filePath, boolean iswebsocket, OnparseLisenter lisenter) {
        this.lisenter = lisenter;
        Locale locale = context.getResources().getConfiguration().locale;
        String language = locale.getLanguage();


        IBmService = new SpeechToText();
        IBmService.setUsernameAndPassword("825c4ccd-8d27-409a-a0b4-a60310f7f7f0", "bmslQgmcxEUr");
        options = new RecognizeOptions.Builder()
                .model("en-US_BroadbandModel")
                .contentType(HttpMediaType.AUDIO_WAV)
                .inactivityTimeout(-1)//
                .timestamps(true)
                .interimResults(true)//recognizeUsingWebSocket
//                .keywords(new String[]{"colorado", "tornado", "tornadoes"})
//                .keywordsThreshold(0.2)
                .build();


        final File file = new File(filePath);
        if (!file.exists()) {
            Log.e(TAG, "startRecognize: 找不到此文件");
            return;
        }
        try {
            if (IBmService != null) {
                Log.e(TAG, "startRecognize: file--" + file.getName());
                if (iswebsocket) {
                    IBmService.recognizeUsingWebSocket(new FileInputStream(file), options, this);
                } else {

                    IBmService.recognize(file, options).enqueue(new ServiceCallback<SpeechResults>() {
                        @Override
                        public void onResponse(SpeechResults response) {
                            if (response != null) {
                                KDBean kdBean = null;

                                int everyLineCount = 8;//指定每行要显示的单词个数

                                List<Transcript> results = response.getResults();
                                if (results != null) {
                                    resultList.clear();
                                    for (int i = 0; i < results.size(); i++) {
                                        List<SpeechAlternative> alternatives = results.get(i).getAlternatives();
                                        if (alternatives.size() > 0) {
                                            SpeechAlternative alternative = alternatives.get(0);//每一行的所有信息
                                            String transcript = alternative.getTranscript();
                                            List<SpeechTimestamp> timestampList = alternative.getTimestamps();

                                            String[] splitArr = transcript.split(" ");
                                            if (splitArr.length <= everyLineCount) {//该行小于everyLineCount个单词 ;如果不指定个数,此处改为true即可
                                                kdBean = new KDBean();
                                                if (transcript != null) {
                                                    kdBean.setLrc(transcript);
                                                }
                                                List<SpeechTimestamp> timestamps = alternative.getTimestamps();
                                                if (timestamps != null && timestamps.size() > 0) {
                                                    Double startTime = timestamps.get(0).getStartTime();
                                                    kdBean.setStart((long) (startTime * 1000));
                                                    Double endTime = timestamps.get(timestamps.size() - 1).getEndTime();
                                                    kdBean.setEnd((long) (endTime * 1000));
                                                }
                                                resultList.add(kdBean);
                                            } else { //大于everyLineCount个单词
                                                int wordCount = splitArr.length; //单词个数
                                                int lineCount;                   //分割完的行数
                                                if (splitArr.length % everyLineCount == 0) {
                                                    lineCount = splitArr.length / everyLineCount;
                                                } else {
                                                    lineCount = splitArr.length / everyLineCount + 1;
                                                }

                                                String lyric = "";
                                                int currentStartLine = 1;//分割的每行的起始位置
                                                int currentLine = 1;      //当前行数
                                                for (int m = 0; m < wordCount; m++) {

                                                    if (currentLine < lineCount) {//不是最后一行

                                                        if ((m + 1) % everyLineCount != 0) {//没到everyLineCount个单词
                                                            lyric += " " + splitArr[m];

                                                        } else if ((m + 1) % everyLineCount == 0) {//已经到了第everyLineCount个
                                                            lyric += " " + splitArr[m];
                                                            kdBean = new KDBean();
                                                            kdBean.setLrc(lyric);
                                                            kdBean.setStart((long) (timestampList.get(currentStartLine).getStartTime() * 1000));
                                                            kdBean.setEnd((long) (timestampList.get(currentLine * everyLineCount - 1).getEndTime() * 1000));
                                                            resultList.add(kdBean);

                                                            lyric = "";//初始化
                                                            currentLine += 1;
                                                            currentStartLine += everyLineCount;

                                                        }

                                                    } else {// 最后一行
                                                        lyric += " " + splitArr[m];
                                                        currentLine = lineCount;
                                                        if (m == splitArr.length - 1) {//最后一个单词
                                                            kdBean = new KDBean();
                                                            kdBean.setLrc(lyric);
                                                            kdBean.setStart((long) (timestampList.get((lineCount - 1) * everyLineCount).getStartTime() * 1000));
                                                            kdBean.setEnd((long) (timestampList.get(wordCount - 1).getEndTime() * 1000));
                                                            resultList.add(kdBean);
                                                        }
                                                    }
                                                }
                                            }//else >10

                                        }

                                    }
                                    if (resultList != null && resultList.size() > 0) {
                                        Message message = new Message();
                                        message.what = SUCCESS;
                                        handler.sendMessage(message);
                                    }

                                }
                                if (resultList.size() == 0) {
//                                    Message message = new Message();
//                                    message.what = IBM_NODATA;
//                                    handler.sendMessage(message);
                                }
                                Log.e(TAG, "onTranscription: resultList" + resultList.toString());
                            }
                        }

                        @Override
                        public void onFailure(Exception e) {
                            Log.e(TAG, "onFailure: " + e.getMessage());
                        }
                    });
                }

            } else {
                Log.e(TAG, "IBmService: 为null");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }


    @Override
    public void onTranscription(SpeechResults speechResults) {
        if (speechResults != null) {
            KDBean kdBean = null;
            List<Transcript> results = speechResults.getResults();
            if (results != null) {
                for (int i = 0; i < results.size(); i++) {
                    kdBean = new KDBean();
                    List<SpeechAlternative> alternatives = results.get(i).getAlternatives();
                    if (alternatives.size() > 0) {
                        SpeechAlternative alternative = alternatives.get(0);
                        String transcript = alternative.getTranscript();
                        if (transcript != null) {
                            kdBean.setLrc(transcript);
                        }
                        List<SpeechTimestamp> timestamps = alternative.getTimestamps();
                        if (timestamps != null && timestamps.size() > 0) {
                            Double startTime = timestamps.get(0).getStartTime();
                            kdBean.setStart((long) (startTime * 1000));
                            Double endTime = timestamps.get(timestamps.size() - 1).getEndTime();
                            kdBean.setEnd((long) (endTime * 1000));
                        }

                    }
                    resultList.add(kdBean);
                }
            }


            Log.e(TAG, "onTranscription: resultList" + resultList.toString());
        }
    }

    @Override
    public void onConnected() {
        Log.e(TAG, "onDisconnected: 开始连接");
    }

    @Override
    public void onError(Exception e) {
        Log.e(TAG, "发生错误: " + e.getMessage());
    }

    @Override
    public void onDisconnected() {

        Log.e(TAG, "onDisconnected: 断开连接");
    }

    @Override
    public void onInactivityTimeout(RuntimeException runtimeException) {
        Log.e(TAG, "不活动时超时: ");
    }

    @Override
    public void onListening() {
        Log.e(TAG, "onListening: ");
    }

    @Override
    public void onTranscriptionComplete() {
        Log.e(TAG, "onTranscriptionComplete: ");
    }


    public interface OnparseLisenter {
        void onSuccess(ArrayList<KDBean> list);
    }

    OnparseLisenter lisenter;


}
